<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
                <el-option v-for="dict in wf_contact_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['biz:wfContact:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="wfContactTableRef"
        v-loading="loading"
        :data="wfContactList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="姓名" prop="name" />
        <el-table-column label="电话" align="center" prop="phone" />
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="wf_contact_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['biz:wfContact:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['biz:wfContact:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['biz:wfContact:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改野火通讯录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="wfContactFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父编号" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="wfContactOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择父编号"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option v-for="dict in wf_contact_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item v-if="form.type === 'staff'" label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>


        <!--        <el-form-item label="野火系统用户id" prop="wfUserId">-->
        <!--          <el-input v-model="form.wfUserId" placeholder="请输入野火系统用户id" />-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WfContact" lang="ts">
import { listWfContact, getWfContact, delWfContact, addWfContact, updateWfContact } from '@/api/biz/wfContact';
import { WfContactVO, WfContactQuery, WfContactForm } from '@/api/biz/wfContact/types';

type WfContactOption = {
  id: number;
  name: string;
  children?: WfContactOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { wf_contact_type } = toRefs<any>(proxy?.useDict('wf_contact_type'));

const wfContactList = ref<WfContactVO[]>([]);
const wfContactOptions = ref<WfContactOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const wfContactFormRef = ref<ElFormInstance>();
const wfContactTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: WfContactForm = {
  id: undefined,
  name: undefined,
  phone: undefined,
  parentId: undefined,
  type: undefined,
  wfUserId: undefined
};

const data = reactive<PageData<WfContactForm, WfContactQuery>>({
  form: { ...initFormData },
  queryParams: {
    name: undefined,
    phone: undefined,
    parentId: undefined,
    type: undefined,
    wfUserId: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '父编号不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '类型(组织，人员)不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询野火通讯录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listWfContact(queryParams.value);
  const data = proxy?.handleTree<WfContactVO>(res.data, 'id', 'parentId');
  if (data) {
    wfContactList.value = data;
    loading.value = false;
  }
};

/** 查询野火通讯录下拉树结构 */
const getTreeselect = async () => {
  const res = await listWfContact();
  wfContactOptions.value = [];
  const data: WfContactOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<WfContactOption>(res.data, 'id', 'parentId');
  wfContactOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  wfContactFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: WfContactVO) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加野火通讯录';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(wfContactList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: WfContactVO[], status: boolean) => {
  data.forEach((item) => {
    wfContactTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: WfContactVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getWfContact(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改野火通讯录';
};

/** 提交按钮 */
const submitForm = () => {
  wfContactFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateWfContact(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addWfContact(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: WfContactVO) => {
  await proxy?.$modal.confirm('是否确认删除野火通讯录编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delWfContact(row.id).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
</script>
